<?php

require_once "database/types/Article.php";

require_once "smarty/SmartyValidate.class.php";

require_once "database/types/Section.php";

require_once "ACBController.php";



/**
 * @author A.J. Janssen
 */
class AdminController extends ACBController
{
    function __construct()
    {
        parent::__construct();
        //Connect paginator
        SmartyPaginate::connect();
    }
    
    function __destruct() 
    {
        //Disconnect paginator
        SmartyPaginate::disconnect();
    }
    
    function displayPage()
    {
        if (empty($_GET['option']))
            $this->display('admin/index.tpl');
        else switch ($_GET['option'])
        {
            case 'manage_articles':
                $this->manageArticles();
                break;
            case 'manage_categories':
                $this->manageCategories();
                break;
            case 'new_article':
                $this->newArticle();
                break;
            case 'edit_article':
                $this->editArticle();
                break;
            case 'edit_section':
                $this->editSection();
                break;
            default:
                $this->display('admin/index.tpl');
        }
    }
    
    private function manageArticles()
    {
        //Init paginator, load articles
        $this->initPaginator();
        $articles = $this->dbc->getAllArticles();
        SmartyPaginate::setTotal(count($articles));
        SmartyPaginate::setUrl($_SERVER['PHP_SELF'] . '?option=manage_articles');
        //Dispose articles not on current page
        $articles = array_slice($articles, SmartyPaginate::getCurrentIndex(), SmartyPaginate::getLimit());
        $this->acb->assign('results', $articles);
        //Display page
        $this->display('admin/manage_articles.tpl');
    }
    
    private function manageCategories()
    {
        //Get categories
        $categories = $this->dbc->getAllCategories();
        //Get sections
        $sections = $this->dbc->getSections();
        //Update categories with currently assigned sectionids
        $this->dbc->enrichMainCategoriesWithAssignedSections($categories);
        if(empty($_POST)) //No input
            $this->initManageCategoriesPage();
        else //Request with input
        {    
            SmartyValidate::connect($this->acb);
            if(SmartyValidate::is_valid($_POST)) // valid input 
            {
                //Input valid -> done with SmartyValidate
                SmartyValidate::disconnect();
                //Process input
                $this->takeCategoryOperation();
                return;
            }
            else // error, redraw the form
                $this->acb->assign($_POST);
        }
        
        //Assign categories
        usort($categories, "cmpCategory");
        $this->acb->assign('categories', $categories);
        //Assign sections
        $this->acb->assign('sections', $sections);
        //Display page
        $this->display('admin/manage_categories.tpl');
    }
    
    private function initManageCategoriesPage()
    {
        SmartyValidate::connect($this->acb, true);
        SmartyValidate::register_criteria('validCategoryName','valid_category_name');
        SmartyValidate::register_criteria('validCategoryChoice','valid_category_choice');
        SmartyValidate::register_criteria('validOperation','valid_operation');
        SmartyValidate::register_validator('fOperation','operation','validOperation');
        SmartyValidate::register_validator('fCategoryChoice','categoryId','validCategoryChoice');
        SmartyValidate::register_validator('fNewName','categoryName','validCategoryName');
        $this->acb->assign('categoryName', "");
        $this->acb->assign('operation', 'add');
    }
    
    private function takeCategoryOperation()
    {
        switch ($_POST['operation'])
        {
            case 'add':
                $this->addNewCategory();
                break;
            case 'delete':
                $this->deleteCategory();
                break;
            case 'rename':
                $this->renameCategory();
                break;
            case 'assign':
                $this->assignCategory();
                break;
            case 'moveUp':
                $this->moveUpCategory();
                break;
            case 'moveDown':
                $this->moveDownCategory();
                break;
        }
        header( 'Location: admin.php?option=manage_categories' ) ;
    }
    
    private function addNewCategory()
    {
        $parentId = intval($_POST['categoryId']);
        $newName = $_POST['categoryName'];
        $this->dbc->addCategory($parentId, $newName);
    }
    
    private function deleteCategory()
    {
        $categoryId = intval($_POST['categoryId']);
        $this->dbc->recursiveCategoryDelete($categoryId);
    }
    
    private function renameCategory()
    {
        $categoryId = intval($_POST['categoryId']);
        $newName = $_POST['categoryName'];
        $this->dbc->renameCategory($categoryId, $newName);
    }
    
    private function assignCategory()
    {
        $categoryId = intval($_POST['categoryId']);
        $sectionId = intval($_POST['assignedSection']);
        $this->dbc->assignToSection($categoryId, $sectionId);
    }
    
    private function moveUpCategory()
    {
        $category = $this->dbc->getCategory(intval($_POST['categoryId']));
        $this->dbc->moveUp($category, true);
    }
    
    private function moveDownCategory()
    {
        $category = $this->dbc->getCategory(intval($_POST['categoryId']));
        $this->dbc->moveDown($category, true);
    }
    
    private function initPaginator()
    {
        SmartyPaginate::setLimit(3);
        SmartyPaginate::assign($this->acb);
    }
    
    private function editSection()
    {
        //load section
        $section = null;
        if (!empty($_GET['section']))
        {
            $section = $this->dbc->getSection($_GET['section']);
            $this->acb->assign('sectionId', $section->id);
        }
        
        if(empty($_POST) && $section != null) //No input and valid section
        {
            $this->initSmartyValidateForSections();
            $this->acb->assign('sectionName', $section->name);
            $this->acb->assign('sectionDescription', $section->description);
        }
        else if($section != null) //Request with input and valid section
        {    
            SmartyValidate::connect($this->acb);
            if(SmartyValidate::is_valid($_POST)) // valid input
            {
                $this->takeEditSection($section->id);
                return;
            } 
            else // error, redraw the form
                $this->acb->assign($_POST);
        }
        $this->display('admin/edit_section.tpl');
    }
    
    private function editArticle()
    {
        //Get categories
        $categories = $this->dbc->getAllCategories();
        //load article
        $article = null;
        if (!empty($_GET['article']))
            $article = $this->dbc->getArticle($_GET['article']);
        if ($article == null || empty($article->created))
        {
            $this->acb->assign('articleText', "");
            $this->acb->assign('articleSubject', "");
        }
        else
        {
            $this->acb->assign('articleId', $article->id);
            $this->acb->assign('articleCategory', $article->parentid);
            $this->acb->assign('articleText', $article->text);
            $this->acb->assign('articleSubject', $article->subject);
        }
        
        if(empty($_POST)) //No input
            $this->initSmartyValidateForArticles();
        else
        {
            SmartyValidate::connect($this->acb);
            if (isset($_POST['deleteArticle']) && $_POST['deleteArticle'] == 'yes')
            {
                SmartyValidate::disconnect();
                if (!empty($article))
                    $this->dbc->deleteArticle ($article->id);
                header( 'Location: admin.php') ;
                $this->acb->display('admin/index.tpl');
                return;
            }
            if(SmartyValidate::is_valid($_POST)) // valid input
            {
                $this->takeEditArticle($article->id);
                return;
            } 
            else // error, redraw the form
                $this->acb->assign($_POST);
        }
        
        //Allow uploading
        $_SESSION['KCFINDER']['disabled'] = false;
        //Set correct uploading folder
        $_SESSION['KCFINDER']['uploadURL'] = "../upload/articles";
        
        $this->acb->assign('categories', $categories);
        
        //Display page
        $this->display('admin/edit_article.tpl');
    }
    
    private function newArticle()
    {
        //Get categories
        $categories = $this->dbc->getAllCategories();
        
        if(empty($_POST)) //No input
        {
            $this->initSmartyValidateForArticles();
            $this->acb->assign('articleText', "");
            $this->acb->assign('articleSubject', "");
        }
        else //Request with input
        {    
            SmartyValidate::connect($this->acb);
            if(SmartyValidate::is_valid($_POST)) // valid input
            {
                $this->takeNewArticle();
                return;
            } 
            else // error, redraw the form
                $this->acb->assign($_POST);
        }
        
        //Allow uploading
        $_SESSION['KCFINDER']['disabled'] = false;
        //Set correct uploading folder
        $_SESSION['KCFINDER']['uploadURL'] = "../upload/articles";
        
        $this->acb->assign('categories', $categories);
        
        //Display page
        $this->display('admin/new_article.tpl');
    }
    
    private function takeEditSection($id)
    {
        //Input valid -> done with SmartyValidate
        SmartyValidate::disconnect();
        //Assemble section object
        $section = $this->getSection();
        $section->id = $id;
        //Update section
        $this->dbc->editSection($section);
        header( 'Location: section.php?section=' . $section->id);
    }
    
    private function takeEditArticle($id)
    {
        //Input valid -> done with SmartyValidate
        SmartyValidate::disconnect();
        //Asemble article object
        $article = $this->getArticle();
        $article->id = $id;
        //Update article
        $this->dbc->editArticle($article);
        header( 'Location: section.php?section=4&article=' . $article->id) ;
    }
    
    private function initSmartyValidateForArticles()
    {
        SmartyValidate::connect($this->acb, true);
        SmartyValidate::register_criteria('validCategory','valid_category');
        SmartyValidate::register_validator('fArticleCategory','articleCategory','validCategory');
        SmartyValidate::register_validator('fArticleSubject','articleSubject','notEmpty');
        SmartyValidate::register_validator('fArticleText','articleText','notEmpty');
    }
    
    private function initSmartyValidateForSections()
    {
        SmartyValidate::connect($this->acb, true);
        SmartyValidate::register_validator('fSectionName','sectionName','notEmpty');
        SmartyValidate::register_validator('fSectionDescription','sectionDescription','notEmpty');
    }
    
    private function takeNewArticle()
    {
        //Input valid -> done with SmartyValidate
        SmartyValidate::disconnect();
        //Asemble article object
        $article = $this->getArticle();
        $article->authorid = $this->auth->getUser()->id;
        $article->position = $this->dbc->getNextPosition($article->parentid);
        //Persist article
        $id = $this->dbc->postArticle($article);
        header( 'Location: section.php?section=4&article=' . $id) ;
    }
    
    private function getArticle()
    {
        $article = new Article;
        $article->subject = $_POST['articleSubject'];
        $article->text = $_POST['articleText'];
        $article->parentid = $_POST['articleCategory'];
        return $article;
    }
    
    private function getSection()
    {
        $section = new Section;
        $section->description = $_POST['sectionDescription'];
        $section->name = $_POST['sectionName'];
        return $section;
    }
    
}

function valid_category_choice($value, $empty, &$params, &$formvars) 
{
    if (empty($formvars) || empty($formvars['operation']))
        return true;
    if ($formvars['operation'] == 'add')
        return intval($formvars['categoryId']) >= 0;
    return intval($formvars['categoryId']) > 0;
}

function valid_category_name($value, $empty, &$params, &$formvars) 
{
    if (empty($formvars) || empty($formvars['operation']))
        return true;
    if ($formvars['operation'] == 'add' || $formvars['operation'] == 'rename')
        return (!empty($formvars['categoryName']) && strlen(trim($formvars['categoryName'])) > 0);
    return true;
}

function valid_category($value, $empty, &$params, &$formvars) 
{
    if (empty($formvars) || empty($formvars['articleCategory']))
        return false;
    $value = intval($formvars['articleCategory']);
    return $value > 0;
}

function valid_operation($value, $empty, &$params, &$formvars) 
{
    if (empty($formvars) || empty($formvars['operation']))
        return false;
    switch ($formvars['operation'])
    {
        case 'add':
        case 'rename':
        case 'delete':
        case 'assign':
        case 'moveDown':
        case 'moveUp':
            return true;
        default:
            return false;
    }
}
?>
